package com.ct.rbac.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ct.rbac.mapper.SysUserRolesMapper;
import com.ct.rbac.orm.SysUserRolesDO;
import com.ct.rbac.repository.ISysUserRolesRespontory;
import com.ct.repository.commons.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author Auto Generator
 * @since 2023-08-13
 */
@Service
public class SysUserRolesRespontoryImpl extends BaseServiceImpl<SysUserRolesMapper, SysUserRolesDO> implements ISysUserRolesRespontory {


    @Override
    public Boolean countBindRoleUser(Long roleId){
        LambdaQueryWrapper<SysUserRolesDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRolesDO::getRoleId, roleId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    /**
     * 判断用户是否绑定角色
     * @param userId
     * @return
     */
    @Override
    public Boolean countBindUserRole(Long userId){
        LambdaQueryWrapper<SysUserRolesDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRolesDO::getUserId, userId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    /**
     * 查询用户对应的角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> findUserRoleIds(Long userId) {
        LambdaQueryWrapper<SysUserRolesDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRolesDO::getUserId, userId);
        List<SysUserRolesDO> list = this.list(lambdaQueryWrapper);
        if(CollectionUtils.isEmpty(list))return new ArrayList<>();
        return list.stream().map(c->c.getRoleId()).collect(Collectors.toList());
    }

    /**
     * 绑定角色
     * @param userId
     * @param roleId
     */
    @Override
    public Boolean saveBindUserRole(Long userId,Long roleId){
        LambdaQueryWrapper<SysUserRolesDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRolesDO::getRoleId,roleId);
        lambdaQueryWrapper.eq(SysUserRolesDO::getUserId,userId);
        long count = this.count(lambdaQueryWrapper);
        if(count == 0) {
            SysUserRolesDO sysUserRolesDO = new SysUserRolesDO();
            sysUserRolesDO.setRoleId(roleId);
            sysUserRolesDO.setUserId(userId);
            this.save(sysUserRolesDO);
        }

        return false;
    }

    /**
     * 取消绑定
     * @param userId
     * @param roleId
     */
    @Override
    public Boolean  cancleBindUserRole(Long userId,Long roleId){
        LambdaQueryWrapper<SysUserRolesDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRolesDO::getRoleId,roleId);
        lambdaQueryWrapper.eq(SysUserRolesDO::getUserId,userId);
        return this.remove(lambdaQueryWrapper);
    }

}

